<script setup>
import { ref } from 'vue'

const formData = ref({
  password: ''
})
const ruleFormRef = ref()
const rules = ref({
  password: [
    {
      validator: checkPassword,
      trigger: 'change'
    }
  ]
})
const level = ref([])

function checkPassword(rule, value, callback) {
  level.value = []
  if (!value) {
    return callback(new Error('请输入密码'))
  }
  // 全部为数字
  const regNum = /^\d+$/
  // 全部为字母
  const regLetter = /^[a-zA-Z]+$/
  // 全部为符号
  const regSymbol = /^[^a-zA-Z0-9]+$/
  // 数字 + 英文
  const regNumAndLetter = /^[a-zA-Z0-9]+$/
  // 数字 + 符号
  const regNumAndSymbol = /^[^a-zA-Z]+$/
  // 英文 + 符号
  const regLetterAndSymbol = /^[^0-9]$/

  // 满足一种，为简单
  if (regNum.test(value) || regLetter.test(value) || regSymbol.test(value)) {
    level.value = ['low']
  } else if (regNumAndLetter.test(value)) {
    // 数字 + 英文
    level.value = ['low', 'middle']
  } else if (regNumAndSymbol.test(value)) {
    // 数字 + 符号
    level.value = ['low', 'middle']
  } else if (regLetterAndSymbol.test(value)) {
    // 英文 + 符号
    level.value = ['low', 'middle']
  } else {
    level.value = ['low', 'middle', 'high']
  }

  callback()
}
</script>

<template>
  <div class="wrapper">
    <el-form :model="formData" ref="ruleFormRef" :rules="rules">
      <el-form-item prop="password">
        <el-input type="text" v-model="formData.password"></el-input>
        <div class="intensity">
          <span class="pwdInfo">密码强度</span>
          <span class="line" :class="[level.includes('low') ? 'low' : '']"></span>
          <span class="line" :class="[level.includes('middle') ? 'middle' : '']"></span>
          <span class="line" :class="[level.includes('high') ? 'high' : '']"></span>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.intensity {
  display: flex;
  align-items: center;
}

.intensity .pwdInfo {
  font-size: 14px;
  margin-right: 10px;
}

.intensity .line {
  display: inline-block;
  width: 48px;
  height: 4px;
  background: #d8d8d8;
  border-radius: 3px;
  margin-right: 8px;
}

.intensity .low {
  background: #f4664a;
}

.intensity .middle {
  background: #ffb700;
}

.intensity .high {
  background: #2cbb79;
}
</style>
